package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;


    // 角色新增或修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value={"role:saveOrUpdate","角色保存或修改"},logical= Logical.OR)
    public JsonResult saveOrUpdate(Role role, Long[] permissionIds) {
        try {
            if (role.getId() != null) {
                roleService.update(role, permissionIds);
            } else {
                roleService.save(role, permissionIds);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"保存或编辑失败");
        }
        return new JsonResult(true,"保存或编辑成功");
    }

    // 去新增页面
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        List<Permission> permissions = permissionService.list();
        model.addAttribute("permissions", permissions);
        if (id != null) {
            Role role = roleService.get(id);
            model.addAttribute("role", role);
        }
        return "role/input"; // /WEB-INF/views/role/input.jsp
    }

    // 删除角色数据
    @RequestMapping("/delete")
    @RequiresPermissions(value={"role:delete","角色删除"},logical= Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            roleService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"删除失败");
        }
        return new JsonResult(true,"删除成功");
    }

    // 查询所有角色数据
    @RequestMapping("/list")
    @RequiresPermissions(value={"role:list","角色列表"},logical= Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        PageInfo query = roleService.query(qo);
        model.addAttribute("pageResult", query);
        return "role/list";
    }
}
